package android.com.test;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private TextView tv_progress;
    private ProgressBar progressBar;

    private String downloadUrl = "http://acj3.pc6.com/pc6_soure/2018-10/com.taobao.taobao_214.apk";
    private int totalLength = 0;
    private int downloadLength = 0;
    private String downloadProgress = null;

    private File desPath = null;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            int status = msg.what;
            String obj = (String) msg.obj;
            if (status == 1){
                // 下载成功
                Toast.makeText(MainActivity.this,"下载成功,开始安装",Toast.LENGTH_LONG).show();
                installApkFile();
            }else if (status == 0){
                // 下载失败
                Toast.makeText(MainActivity.this,"下载失败," + obj,Toast.LENGTH_LONG).show();
            }else if (status == -1) {
                // 开始下载
                Toast.makeText(MainActivity.this,"开始下载",Toast.LENGTH_LONG).show();
                download();
            }else {
                // 下载中
                String totalSize = Formatter.formatFileSize(MainActivity.this,totalLength);
                String downloadSize = Formatter.formatFileSize(MainActivity.this,downloadLength);
                float pro = (float) downloadLength/totalLength;
                downloadProgress = (float)(pro * 100.0) + "%";
                String tip = "总大小:" + totalSize +
                        " 当前下载:" + downloadSize +" " + "下载进度:" + downloadProgress;
                tv_progress.setText(tip);
                progressBar.setProgress((int)(pro * 100));
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_progress = findViewById(R.id.progressTextView);
        progressBar = findViewById(R.id.progressBar);

        File apkPath = new File(getFilesDir(),"download");
        desPath = new File(getFilesDir(),"taobao.apk");

        if (!apkPath.exists()){
            apkPath.mkdir();
        }

        if (!desPath.exists()){
            try {
                boolean createDirectorySucc = desPath.createNewFile();
                if (createDirectorySucc){
                    Toast.makeText(this,"创建apk文件成功",Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(this,"创建apk文件失败",Toast.LENGTH_LONG).show();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            installApkFile();
            Toast.makeText(this,"apk文件已经存在",Toast.LENGTH_LONG).show();
        }
    }

    public void startDownload(View view){
        getTotalLength();
    }

    public void getTotalLength(){
        new Thread(){
            @Override
            public void run() {
                HttpURLConnection connection = null;

                try {
                    URL url = new URL(downloadUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    int code = connection.getResponseCode();

                    if (code == 200){
                        totalLength = connection.getContentLength();
                        Message msg = Message.obtain();
                        msg.what = -1;
                        handler.sendMessage(msg);
                    }else {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        msg.obj = "错误码:" + code;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                    Message msg = Message.obtain();
                    msg.what = 0;
                    msg.obj = "获取文件大小出现异常";
                    handler.sendMessage(msg);
                }finally {
                    connection.disconnect();
                }
            }
        }.start();
    }

    public void download(){
        new Thread(){
            @Override
            public void run() {
                HttpURLConnection connection = null;
                InputStream inputStream = null;
                FileOutputStream outputStream = null;

                try {
                    URL url = new URL(downloadUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    int code = connection.getResponseCode();

                    if (code == 200){
                        inputStream = connection.getInputStream();
                        outputStream = new FileOutputStream(desPath);
                        byte[] buffer = new byte[1024 * 1024 * 8];
                        int length = -1;

                        while ((length = inputStream.read(buffer)) != -1){
                            outputStream.write(buffer,0,length);

                            downloadLength += length;

                            Message msg = Message.obtain();
                            msg.what = -2;
                            handler.sendMessage(msg);
                        }

                        Message msg = Message.obtain();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }else {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        msg.obj = "错误码:" + code;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                    Message msg = Message.obtain();
                    msg.what = 0;
                    msg.obj = "下载出现异常";
                    handler.sendMessage(msg);
                }finally {
                    try {
                        if (outputStream != null){
                            outputStream.close();
                        }

                        if (inputStream != null){
                            inputStream.close();
                        }

                        if (connection != null){
                            connection.disconnect();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public void installApkFile() {
        // 首先修改apk权限为可读写,否则会提示解析包出现问题
        String[] command = {"chmod", "777", desPath.getPath()};
        ProcessBuilder builder = new ProcessBuilder(command);
        try {
            builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setDataAndType(Uri.parse("file://" + desPath.getPath()),
                "application/vnd.android.package-archive");
        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(installIntent);

        // 安装apk
//        Intent installIntent = new Intent(Intent.ACTION_VIEW);
//        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
//            // 系统版本大于 android 7.0
//
//            Uri contentUri = FileProvider.getUriForFile(
//                    getApplicationContext()
//                    , "android.com.test.fileprovider"
//                    , desPath);
//            installIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//
//            //添加这一句表示对目标应用临时授权该Uri所代表的文件
//            installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        }else {
//            // 小于7.0 版本
//            installIntent.setDataAndType(Uri.parse("file://" + desPath.getPath()),
//                    "application/vnd.android.package-archive");
//        }
//
//        startActivity(installIntent);
    }
}
